//
//  YZhangdianxinxiViewController.m
//  shijianpinggu
//
//  Created by apple on 2017/11/2.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YZhangdianxinxiViewController.h"
#import "YEventTableViewCell.h"
#import "YEventListTableViewController.h"
#import "eventModel.h"
@interface YZhangdianxinxiViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataAr;
@end

@implementation YZhangdianxinxiViewController
-(NSMutableArray *)dataAr{
    if(_dataAr==nil){
        self.dataAr = [[NSMutableArray alloc] init];
    }
    return _dataAr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"YEventTableViewCell" bundle:nil] forCellReuseIdentifier:@"eventCell"];
    
    // 设置导航栏背景
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"jiance_top"] forBarMetrics:UIBarMetricsDefault];
    //去掉返回按钮上的文字
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
    // 设置状态栏
    [UIApplication sharedApplication].statusBarStyle = UIBarStyleBlackOpaque;
    
    //    隐藏UINavigationController
    //self.navigationController.navigationBarHidden = YES;
    self.navigationItem.title = @"监测结果";
    [self loadDataFormUrl];
}

//请求数据
-(void)loadDataFormUrl{
    
    
    NSDictionary *parameter = @{@"virtual_group_id":self.webid,@"WebUrl":self.weburl};
    
    
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexApp/siteinfos" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        if (dic) {
            
            
            NSLog(@"%@", dic);
//            NSArray *evAr = dic[@"event"];
            NSArray *evAr = dic[@"event"];
            
            NSMutableArray *eventArray = [[NSMutableArray alloc] init];
            for (int i=0; i<[evAr count]; i++) {
                for (id f in [evAr objectAtIndex:i]) {
                    if(![f isEqualToString:@"dangernum"]){
                        [eventArray insertObject:[[evAr objectAtIndex:i] valueForKey:f] atIndex:0];
                    }
                        
                    }
                }
            for (NSDictionary *dict in eventArray) {
                eventModel *model = [eventModel new];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataAr addObject:model];
            }
            }
        

        

            [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataAr.count == 0) {
        return 0;
    }else{
        return self.dataAr.count;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YEventTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eventCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.dataAr.count>0) {
        eventModel *eModel = self.dataAr[indexPath.row];
        cell.event.text = eModel.name;
        cell.number.text = [[NSString alloc] initWithFormat:@"%@",eModel.total ];
        if ([eModel.total integerValue] >0) {
            [cell.number setTextColor:[UIColor redColor]];
            cell.image.image = [UIImage imageNamed:@"yuan_hh"];
        }else{
            [cell.number setTextColor:[UIColor blackColor]];
            cell.image.image = [UIImage imageNamed:@"yuan_ll"];
            
        }
        
    }
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60
    ;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //self.hidesBottomBarWhenPushed = YES;
    
    YEventListTableViewController *eventLTVC =      [YEventListTableViewController new];
    eventModel *eModel = self.dataAr[indexPath.row];
//    eventLTVC.typeTwo = self.typeTwo;
    eventLTVC.type = eModel.type;
    eventLTVC.site_id = eModel.site_id;
    eventLTVC.eventName = eModel.name;
    if ([eModel.total integerValue] == 0) {
        [self alertWithString:@"暂无此条信息"];
    }else{
        [self showViewController:eventLTVC sender:nil];
    }
}

-(void)alertWithString:(NSString *)string{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
    }];
    [alertC addAction:otherAction];
    [self.navigationController showDetailViewController:alertC sender:nil];
    //[self.navigationController showViewController:alertC sender:nil];
    //    for (int i=0; i<self.navigationController.viewControllers.count; i++) {
    //        if ((self.navigationController.viewControllers[i] == self)) {
    //            [self.navigationController presentViewController:alertC animated:YES completion:nil];
    //        }
    //
    //    }
}

@end
